import React, { useState, useEffect } from 'react';
import api from '../../services/api';
import './WorksPage.css';

function WorksPage({ user, token }) {
    // 基础状态
    const [works, setWorks] = useState([]);
    const [loading, setLoading] = useState(true);
    const [message, setMessage] = useState({ type: '', text: '' });

    // 搜索和筛选状态
    const [searchKeyword, setSearchKeyword] = useState('');
    const [selectedTags, setSelectedTags] = useState([]);
    const [availableTags, setAvailableTags] = useState([]);
    const [activeTab, setActiveTab] = useState('all'); // all, owned, created, purchased

    // 模态框状态
    const [showCreateModal, setShowCreateModal] = useState(false);
    const [showDetailModal, setShowDetailModal] = useState(false);
    const [showPromotionModal, setShowPromotionModal] = useState(false);
    const [selectedWork, setSelectedWork] = useState(null);

    // 个人资源状态
    const [ownedWorks, setOwnedWorks] = useState([]);
    const [createdWorks, setCreatedWorks] = useState([]);
    const [purchasedWorks, setPurchasedWorks] = useState([]);

    // 创建资源表单状态
    const [createForm, setCreateForm] = useState({
        name: '',
        desc: '',
        cost: 50,
        tags: [],
        torrent: null,
        cover: null
    });

    // 促销设置表单状态
    const [promotionForm, setPromotionForm] = useState({
        onSale: false,
        netRate: 1.0,
        costRate: 1.0
    });

    // 标签选择状态
    const [showTagSelector, setShowTagSelector] = useState(false);
    const [availableTagsForCreate, setAvailableTagsForCreate] = useState([]);
    const [loadingTags, setLoadingTags] = useState(false);

    // 权限检查
    const isAdmin = user?.data?.isAdmin || user?.isAdmin;
    const userId = user?.data?.id || user?.id;

    // 添加 token 提取逻辑
    const actualToken = (() => {
        let extractedToken = null;

        // 首先检查传入的 token 是否有效
        if (token && token !== 'undefined' && token !== 'null' && token.trim() !== '') {
            extractedToken = token.trim();
        }
        // 如果传入的 token 无效，尝试从 user.data.token 中提取
        else if (user?.data?.token) {
            extractedToken = user.data.token.trim();
        }

        // 验证 token 格式
        if (extractedToken) {
            console.log('提取到的 token:', extractedToken);
            console.log('Token 长度:', extractedToken.length);
            console.log('Token 开头:', extractedToken.substring(0, 20));
            console.log('Token 结尾:', extractedToken.substring(extractedToken.length - 20));

            // 检查是否是有效的 JWT 格式 (应该有两个点分隔三部分)
            const parts = extractedToken.split('.');
            console.log('Token 分段数量:', parts.length);

            if (parts.length !== 3) {
                console.error('Token 格式不正确，应该有3个部分，实际有:', parts.length);
                return null;
            }

            // 检查每个部分是否是有效的 base64
            for (let i = 0; i < parts.length; i++) {
                if (!parts[i] || parts[i].length === 0) {
                    console.error(`Token 第${i+1}部分为空`);
                    return null;
                }
            }

            return extractedToken;
        }

        return null;
    })();

    // 图片缓存
    const [imageUrls, setImageUrls] = useState(new Map());

    // 获取图片Blob URL的函数
    const fetchImageUrl = async (coverPath, workId) => {
        // 如果已经缓存了，直接返回
        if (imageUrls.has(workId)) {
            return imageUrls.get(workId);
        }

        try {
            console.log('开始获取图片:', coverPath, 'for work:', workId);

            // 使用api.js中的getCover方法
            const blob = await api.getCover(actualToken, coverPath);
            const imageUrl = URL.createObjectURL(blob);

            // 缓存图片URL
            setImageUrls(prev => new Map(prev).set(workId, imageUrl));
            console.log('图片获取成功，已缓存');
            return imageUrl;
        } catch (error) {
            console.error('获取图片失败:', error);
            return null;
        }
    };

    // 图片组件
    const WorkImage = ({ work, className = "work-cover" }) => {
        const [imageUrl, setImageUrl] = useState(null);
        const [loading, setLoading] = useState(true);
        const [error, setError] = useState(false);

        useEffect(() => {
            let mounted = true; // 防止组件卸载后继续设置状态

            const loadImage = async () => {
                if (!work.cover) {
                    setLoading(false);
                    return;
                }

                try {
                    setLoading(true);
                    setError(false);

                    const url = await fetchImageUrl(work.cover, work.id);

                    if (mounted) {
                        if (url) {
                            setImageUrl(url);
                            setError(false);
                        } else {
                            setError(true);
                        }
                    }
                } catch (err) {
                    console.error('加载图片失败:', err);
                    if (mounted) {
                        setError(true);
                    }
                } finally {
                    if (mounted) {
                        setLoading(false);
                    }
                }
            };

            loadImage();

            // 清理函数
            return () => {
                mounted = false;
            };
        }, [work.cover, work.id]);

        if (loading) {
            return (
                <div className={className}>
                    <div className="cover-placeholder loading">
                        ⏳
                    </div>
                </div>
            );
        }

        if (error || !imageUrl) {
            return (
                <div className={className}>
                    <div className="cover-placeholder error">
                        📄
                    </div>
                </div>
            );
        }

        return (
            <div className={className}>
                <img
                    src={imageUrl}
                    alt={work.name}
                    onError={() => {
                        console.error('图片加载错误:', work.cover);
                        setError(true);
                    }}
                />
            </div>
        );
    };

    useEffect(() => {
        if (actualToken) {
            initializeData();
        } else {
            console.error('Token is missing or invalid!');
            showMessage('error', '缺少认证信息，请重新登录');
            setLoading(false);
        }

        // 清理函数：释放所有blob URLs
        return () => {
            imageUrls.forEach(url => {
                if (url && url.startsWith('blob:')) {
                    URL.revokeObjectURL(url);
                }
            });
        };
    }, [actualToken]);

    // 监听activeTab变化
    useEffect(() => {
        if (!actualToken) {
            return;
        }

        console.log('=== activeTab变化触发 ===');
        console.log('切换到标签页:', activeTab);

        if (activeTab === 'owned') {
            fetchOwnedWorks();
        } else if (activeTab === 'created') {
            fetchCreatedWorks();
        } else if (activeTab === 'purchased') {
            fetchPurchasedWorks();
        }
        // 注意：不在这里处理'all'标签页，让selectedTags的useEffect处理
    }, [activeTab, actualToken]);

    // 专门监听selectedTags变化的useEffect，确保标签选择立即生效
    useEffect(() => {
        if (!actualToken) {
            return;
        }

        // 只在"全部资源"标签页处理标签变化
        if (activeTab === 'all') {
            console.log('=== 标签变化触发数据刷新 ===');
            console.log('新的标签列表:', selectedTags);
            console.log('标签数量:', selectedTags.length);

            // 使用当前最新的selectedTags调用fetchWorks
            fetchWorks(selectedTags);
        }
    }, [selectedTags, actualToken]);

    const initializeData = async () => {
        try {
            setLoading(true);
            await Promise.all([
                fetchHotTags(),
                fetchOwnedWorks()
            ]);

            // 如果当前在"全部资源"标签页，初始化时获取数据
            if (activeTab === 'all') {
                await fetchWorks([]);  // 初始时没有选择标签
            }
        } catch (error) {
            console.error('初始化数据失败:', error);
            showMessage('error', '加载数据失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取所有资源 - 使用正确的API接口（可接受参数确保使用最新的标签）
    const fetchWorks = async (tagsToUse = null) => {
        try {
            // 使用传入的标签或当前状态中的标签
            const currentTags = tagsToUse !== null ? tagsToUse : selectedTags;

            console.log('=== 获取资源开始 ===');
            console.log('使用的标签:', currentTags);
            console.log('标签数量:', currentTags.length);

            let result;
            if (currentTags.length > 0) {
                console.log('使用标签搜索:', currentTags);
                // 使用正确的API接口：GET /work/get_works_with_tags
                result = await api.getWorksWithTags(actualToken, currentTags, 'createTime', 1, 100);
                console.log('标签搜索结果:', result);
            } else {
                console.log('获取所有资源');
                result = await api.getWorks(actualToken, 'createTime', 1, 100);
                console.log('获取所有资源结果:', result);
            }

            if (result.status === 1 || result.status === 200) {
                // 根据API文档，数据在result.data.records中
                const works = result.data?.records || result.data || [];
                console.log('解析后的资源列表:', works);
                console.log('资源数量:', works.length);

                // 打印分页信息
                if (result.data?.total !== undefined) {
                    console.log('总资源数:', result.data.total);
                    console.log('当前页:', result.data.current);
                    console.log('总页数:', result.data.pages);
                }

                setWorks(works);

                if (currentTags.length > 0 && works.length === 0) {
                    showMessage('info', `没有找到包含标签 "${currentTags.join(', ')}" 的资源`);
                }
            } else {
                console.error('API返回错误状态:', result.status, result.msg);
                showMessage('error', result.msg || '获取资源失败');
                setWorks([]);
            }
        } catch (error) {
            console.error('获取资源失败:', error);
            showMessage('error', '获取资源失败: ' + error.message);
            setWorks([]);
        }
    };

    // 获取热门标签
    const fetchHotTags = async () => {
        try {
            const result = await api.getHottestTags(actualToken);
            if (result.status === 1 || result.status === 200) {
                setAvailableTags(result.data || []);
            }
        } catch (error) {
            console.error('获取热门标签失败:', error);
        }
    };

    // 获取拥有的资源
    const fetchOwnedWorks = async () => {
        try {
            const result = await api.getPossessWork(actualToken);
            if (result.status === 1 || result.status === 200) {
                setOwnedWorks(result.data || []);
            }
        } catch (error) {
            console.error('获取拥有的资源失败:', error);
        }
    };

    // 获取创建的资源
    const fetchCreatedWorks = async () => {
        try {
            const result = await api.getUserCreatedWork(actualToken);
            if (result.status === 1 || result.status === 200) {
                setCreatedWorks(result.data || []);
            }
        } catch (error) {
            console.error('获取创建的资源失败:', error);
        }
    };

    // 获取购买的资源
    const fetchPurchasedWorks = async () => {
        try {
            const result = await api.getUserPurchasedWork(actualToken);
            if (result.status === 1 || result.status === 200) {
                setPurchasedWorks(result.data || []);
            }
        } catch (error) {
            console.error('获取购买的资源失败:', error);
        }
    };

    // 搜索资源
    const handleSearch = async () => {
        if (!searchKeyword.trim()) {
            fetchWorks();
            return;
        }

        try {
            setLoading(true);
            const result = await api.searchByName(actualToken, searchKeyword);

            if (result.status === 1 || result.status === 200) {
                setWorks(result.data || []);
            }
        } catch (error) {
            console.error('搜索失败:', error);
            showMessage('error', '搜索失败');
        } finally {
            setLoading(false);
        }
    };

    // 创建资源 - 匹配后端@RequestPart接口
    const handleCreateWork = async () => {
        try {
            if (!createForm.name || !createForm.torrent) {
                showMessage('error', '请填写资源名称并上传种子文件');
                return;
            }

            // 验证文件类型
            if (!createForm.torrent.name.endsWith('.torrent')) {
                showMessage('error', '请上传.torrent格式的种子文件');
                return;
            }

            if (createForm.cover && !createForm.cover.type.startsWith('image/')) {
                showMessage('error', '请上传图片格式的封面文件');
                return;
            }

            // 构建 CreateWorkDto 对象
            const createWorkDto = {
                name: createForm.name,
                desc: createForm.desc,
                cost: createForm.cost,
                tags: createForm.tags
            };

            console.log('准备创建资源，数据:', {
                createWorkDto,
                torrentFile: createForm.torrent?.name,
                coverFile: createForm.cover?.name
            });

            // 创建FormData，匹配@RequestPart接口
            const formData = new FormData();

            // metadata作为JSON Blob添加，设置Content-Type为application/json
            // 这样后端的@RequestPart("metadata") CreateWorkDto才能正确解析
            const metadataBlob = new Blob([JSON.stringify(createWorkDto)], {
                type: 'application/json'
            });
            formData.append('metadata', metadataBlob);

            // torrent文件（必需）
            formData.append('torrent', createForm.torrent);

            // cover文件（可选，后端允许为空）
            if (createForm.cover) {
                formData.append('cover', createForm.cover);
            }

            console.log('开始创建资源...');
            const result = await api.createWork(actualToken, formData);

            if (result.status === 1 || result.status === 200) {
                showMessage('success', '资源创建成功');
                setShowCreateModal(false);
                resetCreateForm();
                fetchWorks();
                fetchCreatedWorks();
            } else {
                throw new Error(result.msg || '创建资源失败');
            }
        } catch (error) {
            console.error('创建资源失败:', error);
            showMessage('error', error.message || '创建资源失败');
        }
    };

    // 购买资源
    const handlePurchaseWork = async (workId) => {
        try {
            const result = await api.purchaseWork(actualToken, workId);
            if (result.status === 1 || result.status === 200) {
                showMessage('success', '购买成功');
                fetchOwnedWorks();
                fetchPurchasedWorks();
            }
        } catch (error) {
            console.error('购买失败:', error);
            showMessage('error', error.message || '购买失败');
        }
    };

    // 下载资源
    const handleDownloadWork = async (workId) => {
        try {
            await api.getWorkTorrent(actualToken, workId);
            showMessage('success', '下载开始');
        } catch (error) {
            console.error('下载失败:', error);
            showMessage('error', error.message || '下载失败');
        }
    };

    // 删除资源
    const handleDeleteWork = async (workId, isAdmin = false) => {
        if (!window.confirm('确定要删除这个资源吗？')) {
            return;
        }

        try {
            let result;
            if (isAdmin) {
                // 管理员删除
                result = await api.adminDeleteWork(actualToken, workId);
            } else {
                // 用户删除自己的资源
                result = await api.deleteUserWork(actualToken, workId);
            }

            if (result.status === 1 || result.status === 200) {
                showMessage('success', '资源删除成功');
                // 刷新数据
                fetchWorks();
                fetchCreatedWorks();
                fetchOwnedWorks();
                setShowDetailModal(false);
            }
        } catch (error) {
            console.error('删除失败:', error);
            showMessage('error', error.message || '删除失败');
        }
    };

    // 设置促销
    const handleSetPromotion = async () => {
        try {
            const result = await api.setWorkOnSale(
                actualToken,
                selectedWork.id,
                promotionForm.onSale,
                promotionForm.netRate,
                promotionForm.costRate
            );

            if (result.status === 1 || result.status === 200) {
                showMessage('success', '促销设置成功');
                setShowPromotionModal(false);
                fetchWorks();
            }
        } catch (error) {
            console.error('设置促销失败:', error);
            showMessage('error', error.message || '设置促销失败');
        }
    };

    // 标签操作
    const handleTagSelect = (tag) => {
        console.log('=== 标签选择操作 ===');
        console.log('点击的标签:', tag);
        console.log('当前选择的标签:', selectedTags);

        const tagContent = tag.content || tag;
        console.log('标签内容:', tagContent);

        let newSelectedTags;
        if (selectedTags.includes(tagContent)) {
            newSelectedTags = selectedTags.filter(t => t !== tagContent);
            console.log('移除标签:', tagContent);
        } else {
            newSelectedTags = [...selectedTags, tagContent];
            console.log('添加标签:', tagContent);
        }

        console.log('新的标签列表:', newSelectedTags);
        setSelectedTags(newSelectedTags);

        // 移除手动调用fetchWorks，让useEffect处理
    };

    const clearAllTags = () => {
        console.log('=== 清除所有标签 ===');
        setSelectedTags([]);

        // 移除手动调用fetchWorks，让useEffect处理
    };

    // 获取标签列表用于创建资源
    const fetchTagsForCreate = async () => {
        try {
            setLoadingTags(true);
            console.log('=== 获取创建资源标签列表 ===');

            const result = await api.getHottestTags(actualToken);
            console.log('标签列表响应:', result);

            if (result.status === 1 || result.status === 200) {
                setAvailableTagsForCreate(result.data || []);
                setShowTagSelector(true);
                console.log('标签列表获取成功，数量:', result.data?.length);
            } else {
                throw new Error(result.msg || '获取标签列表失败');
            }
        } catch (error) {
            console.error('获取标签列表失败:', error);
            showMessage('error', '获取标签列表失败: ' + error.message);
        } finally {
            setLoadingTags(false);
        }
    };

    // 从标签列表中选择标签
    const selectTagFromList = (tag) => {
        const tagContent = tag.content || tag;

        // 检查是否已经添加过这个标签
        if (!createForm.tags.includes(tagContent)) {
            setCreateForm({
                ...createForm,
                tags: [...createForm.tags, tagContent]
            });
            console.log('添加标签:', tagContent);
        } else {
            showMessage('info', '标签已存在');
        }
    };

    // 手动输入标签（保留原功能）
    const addCustomTag = () => {
        const customTag = prompt('请输入自定义标签:');
        if (customTag && customTag.trim()) {
            const tagContent = customTag.trim();
            if (!createForm.tags.includes(tagContent)) {
                setCreateForm({
                    ...createForm,
                    tags: [...createForm.tags, tagContent]
                });
                console.log('添加自定义标签:', tagContent);
            } else {
                showMessage('info', '标签已存在');
            }
        }
    };

    const removeTag = (tagToRemove) => {
        setCreateForm({
            ...createForm,
            tags: createForm.tags.filter(tag => tag !== tagToRemove)
        });
    };

    // 工具函数
    const showMessage = (type, text) => {
        setMessage({ type, text });
        setTimeout(() => setMessage({ type: '', text: '' }), 3000);
    };

    const resetCreateForm = () => {
        setCreateForm({
            name: '',
            desc: '',
            cost: 50,
            tags: [],
            torrent: null,
            cover: null
        });
        setShowTagSelector(false);
        setAvailableTagsForCreate([]);
    };

    const formatBytes = (bytes) => {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    };

    const formatDate = (dateString) => {
        return new Date(dateString).toLocaleDateString('zh-CN');
    };

    const isWorkOwned = (workId) => {
        return ownedWorks.some(work => work.id === workId);
    };

    const getCurrentWorks = () => {
        switch (activeTab) {
            case 'owned':
                return ownedWorks;
            case 'created':
                return createdWorks;
            case 'purchased':
                return purchasedWorks;
            default:
                return works;
        }
    };

    if (loading) {
        return (
            <div className="loading">
                <div className="loading-spinner"></div>
                加载中...
            </div>
        );
    }

    if (!actualToken) {
        return (
            <div className="works-container">
                <div className="empty-state">
                    <div className="empty-icon">🔒</div>
                    <p>请先登录后再访问资源中心</p>
                </div>
            </div>
        );
    }

    return (
        <div className="works-container">
            {/* 页面头部 */}
            <div className="works-header">
                <div className="works-title">
                    <h1>📦 资源中心</h1>
                    <p>发现、创建和管理您的资源</p>
                </div>
                <button
                    onClick={() => setShowCreateModal(true)}
                    className="create-btn"
                >
                    ➕ 创建资源
                </button>
            </div>

            {/* 消息提示 */}
            {message.text && (
                <div className={`message ${message.type}`}>
                    {message.text}
                </div>
            )}

            {/* 搜索和筛选区域 */}
            <div className="search-filter-area">
                {/* 搜索栏 */}
                <div className="search-bar">
                    <input
                        type="text"
                        placeholder="搜索资源名称..."
                        value={searchKeyword}
                        onChange={(e) => setSearchKeyword(e.target.value)}
                        onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
                        className="search-input"
                    />
                    <button onClick={handleSearch} className="search-btn">
                        🔍 搜索
                    </button>
                </div>

                {/* 标签筛选 */}
                <div className="tags-filter">
                    <div className="tags-label">热门标签：</div>
                    <div className="tags-list">
                        {availableTags.map(tag => (
                            <button
                                key={tag.id}
                                onClick={() => handleTagSelect(tag)}
                                className={`tag-btn ${selectedTags.includes(tag.content) ? 'active' : ''}`}
                            >
                                {tag.content}
                            </button>
                        ))}
                    </div>
                    {selectedTags.length > 0 && (
                        <button
                            onClick={clearAllTags}
                            className="clear-tags-btn"
                        >
                            ❌ 清除筛选
                        </button>
                    )}
                </div>
            </div>

            {/* 标签页 */}
            <div className="tabs-container">
                <div className="tabs">
                    <button
                        onClick={() => setActiveTab('all')}
                        className={`tab ${activeTab === 'all' ? 'active' : ''}`}
                    >
                        🌍 全部资源
                    </button>
                    <button
                        onClick={() => setActiveTab('owned')}
                        className={`tab ${activeTab === 'owned' ? 'active' : ''}`}
                    >
                        💼 我的资源
                    </button>
                    <button
                        onClick={() => setActiveTab('created')}
                        className={`tab ${activeTab === 'created' ? 'active' : ''}`}
                    >
                        ✨ 我创建的
                    </button>
                    <button
                        onClick={() => setActiveTab('purchased')}
                        className={`tab ${activeTab === 'purchased' ? 'active' : ''}`}
                    >
                        🛒 我购买的
                    </button>
                </div>
            </div>

            {/* 资源列表 */}
            <div className="works-grid">
                {getCurrentWorks().map(work => (
                    <div key={work.id} className="work-card">
                        {/* 促销标识 */}
                        {work.onSale && (
                            <div className="promotion-badge">
                                {work.costRate < 1 ? `${Math.round(work.costRate * 100) / 10}折促销中` : '免费'}
                            </div>
                        )}

                        {/* 拥有标识 */}
                        {isWorkOwned(work.id) && (
                            <div className="owned-badge">已拥有</div>
                        )}

                        {/* 资源封面 - 使用新的图片组件 */}
                        <WorkImage work={work} className="work-cover" />

                        {/* 资源信息 */}
                        <div className="work-info">
                            <h3 className="work-name">{work.name}</h3>
                            <p className="work-description">
                                {work.description || '暂无描述'}
                            </p>

                            <div className="work-meta">
                                <div className="meta-item">
                                    <span className="meta-label">大小：</span>
                                    <span className="meta-value">{formatBytes(work.size)}</span>
                                </div>
                                <div className="meta-item">
                                    <span className="meta-label">价格：</span>
                                    <span className="meta-value">
                                        {work.onSale && work.costRate < 1
                                            ? `${Math.round(work.cost * work.costRate)} (原价${work.cost})`
                                            : work.cost
                                        } 魔法值
                                    </span>
                                </div>
                                <div className="meta-item">
                                    <span className="meta-label">下载次数：</span>
                                    <span className="meta-value">{work.download}</span>
                                </div>
                                <div className="meta-item">
                                    <span className="meta-label">创建时间：</span>
                                    <span className="meta-value">{formatDate(work.createTime)}</span>
                                </div>
                            </div>
                        </div>

                        {/* 操作按钮 */}
                        <div className="work-actions">
                            <button
                                onClick={() => {
                                    setSelectedWork(work);
                                    setShowDetailModal(true);
                                }}
                                className="action-btn detail-btn"
                            >
                                📋 详情
                            </button>

                            {isWorkOwned(work.id) ? (
                                <button
                                    onClick={() => handleDownloadWork(work.id)}
                                    className="action-btn download-btn"
                                >
                                    ⬇️ 下载
                                </button>
                            ) : (
                                <button
                                    onClick={() => handlePurchaseWork(work.id)}
                                    className="action-btn purchase-btn"
                                >
                                    💰 购买
                                </button>
                            )}

                            {/* 管理员和创建者可以删除 */}
                            {(isAdmin || work.userId === userId) && (
                                <button
                                    onClick={() => handleDeleteWork(work.id, isAdmin)}
                                    className="action-btn delete-btn"
                                >
                                    🗑️ 删除
                                </button>
                            )}

                            {/* 管理员可以设置促销 */}
                            {isAdmin && (
                                <button
                                    onClick={() => {
                                        setSelectedWork(work);
                                        setPromotionForm({
                                            onSale: work.onSale,
                                            netRate: work.netRate || 1.0,
                                            costRate: work.costRate || 1.0
                                        });
                                        setShowPromotionModal(true);
                                    }}
                                    className="action-btn promotion-btn"
                                >
                                    🏷️ 促销
                                </button>
                            )}
                        </div>
                    </div>
                ))}
            </div>

            {getCurrentWorks().length === 0 && (
                <div className="empty-state">
                    <div className="empty-icon">📦</div>
                    <p>暂无资源</p>
                </div>
            )}

            {/* 创建资源模态框 */}
            {showCreateModal && (
                <div className="modal-overlay" onClick={() => setShowCreateModal(false)}>
                    <div className="modal" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <h2>创建新资源</h2>
                            <button
                                onClick={() => setShowCreateModal(false)}
                                className="close-btn"
                            >
                                ❌
                            </button>
                        </div>

                        <div className="modal-content">
                            <div className="form-group">
                                <label>资源名称：</label>
                                <input
                                    type="text"
                                    value={createForm.name}
                                    onChange={(e) => setCreateForm({...createForm, name: e.target.value})}
                                    placeholder="输入资源名称"
                                />
                            </div>

                            <div className="form-group">
                                <label>资源描述：</label>
                                <textarea
                                    value={createForm.desc}
                                    onChange={(e) => setCreateForm({...createForm, desc: e.target.value})}
                                    placeholder="输入资源描述"
                                    rows="3"
                                />
                            </div>

                            <div className="form-group">
                                <label>价格（魔法值）：</label>
                                <input
                                    type="number"
                                    value={createForm.cost}
                                    onChange={(e) => setCreateForm({...createForm, cost: parseInt(e.target.value)})}
                                    min="0"
                                />
                            </div>

                            <div className="form-group">
                                <label>标签：</label>
                                <div className="tag-selection-container">
                                    <div className="tag-actions">
                                        <button
                                            type="button"
                                            onClick={fetchTagsForCreate}
                                            className="fetch-tags-btn"
                                            disabled={loadingTags}
                                        >
                                            {loadingTags ? '加载中...' : '📋 选择标签'}
                                        </button>
                                        <button
                                            type="button"
                                            onClick={addCustomTag}
                                            className="add-custom-tag-btn"
                                        >
                                            ✏️ 自定义标签
                                        </button>
                                    </div>

                                    {/* 标签选择器 */}
                                    {showTagSelector && (
                                        <div className="tag-selector">
                                            <div className="tag-selector-header">
                                                <span>选择标签：</span>
                                                <button
                                                    type="button"
                                                    onClick={() => setShowTagSelector(false)}
                                                    className="close-selector-btn"
                                                >
                                                    ❌
                                                </button>
                                            </div>
                                            <div className="available-tags">
                                                {availableTagsForCreate.map(tag => (
                                                    <button
                                                        key={tag.id}
                                                        type="button"
                                                        onClick={() => selectTagFromList(tag)}
                                                        className={`available-tag-btn ${
                                                            createForm.tags.includes(tag.content) ? 'selected' : ''
                                                        }`}
                                                        disabled={createForm.tags.includes(tag.content)}
                                                    >
                                                        {tag.content}
                                                    </button>
                                                ))}
                                            </div>
                                        </div>
                                    )}

                                    {/* 已选择的标签显示 */}
                                    <div className="selected-tags">
                                        {createForm.tags.map(tag => (
                                            <span key={tag} className="selected-tag">
                                                {tag}
                                                <button
                                                    type="button"
                                                    onClick={() => removeTag(tag)}
                                                    className="remove-tag-btn"
                                                >
                                                    ❌
                                                </button>
                                            </span>
                                        ))}
                                    </div>
                                </div>
                            </div>

                            <div className="form-group">
                                <label>种子文件：</label>
                                <input
                                    type="file"
                                    accept=".torrent"
                                    onChange={(e) => setCreateForm({...createForm, torrent: e.target.files[0]})}
                                />
                            </div>

                            <div className="form-group">
                                <label>封面图片（可选）：</label>
                                <input
                                    type="file"
                                    accept="image/*"
                                    onChange={(e) => setCreateForm({...createForm, cover: e.target.files[0]})}
                                />
                            </div>
                        </div>

                        <div className="modal-actions">
                            <button
                                onClick={() => setShowCreateModal(false)}
                                className="cancel-btn"
                            >
                                取消
                            </button>
                            <button
                                onClick={handleCreateWork}
                                className="submit-btn"
                            >
                                创建资源
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* 资源详情模态框 */}
            {showDetailModal && selectedWork && (
                <div className="modal-overlay" onClick={() => setShowDetailModal(false)}>
                    <div className="modal large" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <h2>资源详情</h2>
                            <button
                                onClick={() => setShowDetailModal(false)}
                                className="close-btn"
                            >
                                ❌
                            </button>
                        </div>

                        <div className="modal-content">
                            <div className="detail-grid">
                                <div className="detail-left">
                                    <WorkImage work={selectedWork} className="detail-cover" />
                                </div>

                                <div className="detail-right">
                                    <h3>{selectedWork.name}</h3>
                                    <p className="detail-description">
                                        {selectedWork.description || '暂无描述'}
                                    </p>

                                    <div className="detail-meta-grid">
                                        <div className="detail-meta-item">
                                            <span className="label">文件大小：</span>
                                            <span className="value">{formatBytes(selectedWork.size)}</span>
                                        </div>

                                        <div className="detail-meta-item">
                                            <span className="label">价格：</span>
                                            <span className="value">
                                                {selectedWork.onSale && selectedWork.costRate < 1
                                                    ? `${Math.round(selectedWork.cost * selectedWork.costRate)} (原价${selectedWork.cost})`
                                                    : selectedWork.cost
                                                } 魔法值
                                            </span>
                                        </div>

                                        <div className="detail-meta-item">
                                            <span className="label">下载次数：</span>
                                            <span className="value">{selectedWork.download}</span>
                                        </div>

                                        <div className="detail-meta-item">
                                            <span className="label">创建时间：</span>
                                            <span className="value">{formatDate(selectedWork.createTime)}</span>
                                        </div>

                                        <div className="detail-meta-item">
                                            <span className="label">Info Hash：</span>
                                            <span className="value hash">{selectedWork.infoHash}</span>
                                        </div>

                                        {selectedWork.onSale && (
                                            <div className="detail-meta-item">
                                                <span className="label">促销状态：</span>
                                                <span className="value promotion">
                                                    {selectedWork.costRate < 1
                                                        ? `${Math.round(selectedWork.costRate * 100) / 10}折促销中`
                                                        : '免费促销中'
                                                    }
                                                </span>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="modal-actions">
                            {isWorkOwned(selectedWork.id) ? (
                                <button
                                    onClick={() => handleDownloadWork(selectedWork.id)}
                                    className="action-btn download-btn"
                                >
                                    ⬇️ 下载资源
                                </button>
                            ) : (
                                <button
                                    onClick={() => handlePurchaseWork(selectedWork.id)}
                                    className="action-btn purchase-btn"
                                >
                                    💰 购买资源
                                </button>
                            )}
                        </div>
                    </div>
                </div>
            )}

            {/* 促销设置模态框 */}
            {showPromotionModal && selectedWork && isAdmin && (
                <div className="modal-overlay" onClick={() => setShowPromotionModal(false)}>
                    <div className="modal" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <h2>设置促销</h2>
                            <button
                                onClick={() => setShowPromotionModal(false)}
                                className="close-btn"
                            >
                                ❌
                            </button>
                        </div>

                        <div className="modal-content">
                            <div className="form-group">
                                <label>
                                    <input
                                        type="checkbox"
                                        checked={promotionForm.onSale}
                                        onChange={(e) => setPromotionForm({
                                            ...promotionForm,
                                            onSale: e.target.checked
                                        })}
                                    />
                                    启用促销
                                </label>
                            </div>

                            {promotionForm.onSale && (
                                <>
                                    <div className="form-group">
                                        <label>价格折扣（1.0为原价，0.5为5折）：</label>
                                        <input
                                            type="number"
                                            min="0"
                                            max="1"
                                            step="0.1"
                                            value={promotionForm.costRate}
                                            onChange={(e) => setPromotionForm({
                                                ...promotionForm,
                                                costRate: parseFloat(e.target.value)
                                            })}
                                        />
                                    </div>

                                    <div className="form-group">
                                        <label>下载速度倍率（1.0为正常速度）：</label>
                                        <input
                                            type="number"
                                            min="0.1"
                                            max="10"
                                            step="0.1"
                                            value={promotionForm.netRate}
                                            onChange={(e) => setPromotionForm({
                                                ...promotionForm,
                                                netRate: parseFloat(e.target.value)
                                            })}
                                        />
                                    </div>
                                </>
                            )}

                            <div className="promotion-preview">
                                <h4>促销预览：</h4>
                                <p>
                                    {promotionForm.onSale
                                        ? `${selectedWork.name} - ${promotionForm.costRate < 1
                                            ? `${Math.round(promotionForm.costRate * 100) / 10}折促销中`
                                            : '免费促销中'}`
                                        : '无促销'
                                    }
                                </p>
                            </div>
                        </div>

                        <div className="modal-actions">
                            <button
                                onClick={() => setShowPromotionModal(false)}
                                className="cancel-btn"
                            >
                                取消
                            </button>
                            <button
                                onClick={handleSetPromotion}
                                className="submit-btn"
                            >
                                设置促销
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

export default WorksPage;